package cn.elves.model.rule.service.rules;

import cn.elves.model.rule.entity.constant.RootNodeConstants;
import cn.elves.model.rule.entity.constant.RuleLimitTypeConstants;
import cn.elves.model.rule.entity.dto.RuleTreeNodeDTO;
import cn.elves.model.rule.entity.dto.RuleTreeNodeLineDTO;

import java.util.List;
import java.util.Map;

/**
 * @description: 规则基础抽象类
 */
public abstract class BaseRule implements RuleFilter {


    private String ruleKey = "";

    @Override
    public RuleTreeNodeDTO filter(String matterValue, List<RuleTreeNodeLineDTO> treeNodeLineInfoList) {
        for (RuleTreeNodeLineDTO nodeLine : treeNodeLineInfoList) {
            if (decisionLogic(matterValue, nodeLine)) {
                return nodeLine.getRuleTreeNodeDTO();
            }
        }
        return RootNodeConstants.EMPTY_NODE;
    }

    /**
     * 获取规则比对值
     *
     * @param decisionMatter 决策物料
     * @return 比对值
     */
    @Override
    public String matterValue(Map<String, Object> decisionMatter) {
        return decisionMatter.get(ruleKey).toString();
    }

    @Override
    public String getRuleKey() {
        return ruleKey;
    }

    private boolean decisionLogic(String matterValue, RuleTreeNodeLineDTO nodeLine) {
        switch (nodeLine.getRuleLimitType()) {
            case RuleLimitTypeConstants.EQUAL:
                return matterValue.equals(nodeLine.getRuleLimitValue());
            case RuleLimitTypeConstants.GT:
                return Double.parseDouble(matterValue) > Double.parseDouble(nodeLine.getRuleLimitValue());
            case RuleLimitTypeConstants.LT:
                return Double.parseDouble(matterValue) < Double.parseDouble(nodeLine.getRuleLimitValue());
            case RuleLimitTypeConstants.GE:
                return Double.parseDouble(matterValue) >= Double.parseDouble(nodeLine.getRuleLimitValue());
            case RuleLimitTypeConstants.LE:
                return Double.parseDouble(matterValue) <= Double.parseDouble(nodeLine.getRuleLimitValue());
            default:
                return false;
        }
    }

}
